var videoCode = 'appvideo';
var pageNum = 1;
var itemNum = 20;
var status = ""
var insretPolicy = document.getElementById("insretPolicy");
var countNum = 0;
var token = "";
var pageflag = "";
var carCode = "";
var derviceNum = "";
var otherInfo = "";
var imgStr = "";
var code = "";
var errorPath = "";
var upPhoto = document.getElementById("upPhoto");

var isSelectPhoto = false;
var isErrorPhoto = false;

(function(e) {

	mui.init({
		keyEventBind: {
			backbutton: true //开启back按键监听
		}
	});

	setPxPerRem();
	mui.plusReady(function() {
		pageflag = getQueryString("pageflag");
		status = getQueryString("itemID");

		if(isEmpty(status)) {
			status = "未出库";
		}

		carCode = getQueryString("carNo");
		code = getQueryString("code");
		derviceNum = getQueryString("tel");

		$("#projectTitle").html(code);
		$("#carNo").html(carCode);
		$("#tel").html(derviceNum);
		var nextStatus = status;
		for(var i = 0; i < statusArr.length; i++) {
			if(statusArr[i] == status) {
				nextStatus = statusArr[i + 1];
			}
		}
		$("#changeStatus").html(nextStatus);

		mui.back = function(event) {
			var cw = plus.webview.currentWebview();
			var parentView = plus.webview.getWebviewById(pageflag);
			mui.fire(parentView, 'backPullupRefresh', "");
			cw.close();
		};

	});

})(mui);

//下拉刷新
var isRefresh = false;

function pulldownRefresh() {
	removeLi("policyList");
	isRefresh = true;
	pageNum = 1;
	if(isHaveNet()) {
		getPoilcyList();
	} else {
		mui.toast("无网络连接！");
	}
}

//上拉加载
var isLoad = false;

function pullupRefresh() {
	isLoad = true;

	if(isHaveNet()) {
		getPoilcyList();
	} else {
		mui.toast("无网络连接！");
	}
}

function UpdateCarStatus() {
	token = localStorage.getItem("pid");
	console.log(imgStr.length);

	var currentStatus = $("#changeStatus").html();
	var pjson = {
		status: currentStatus,
		PaiCheCode: code,
		notes: otherInfo,
		pid: token,
		byteFileStream1: imgPath
	};

	console.log(JSON.stringify(pjson));

	var jsonData = {
		op: "UpdateCarStatus",
		pjson: JSON.stringify(pjson)
	}

	var opts = {
		url: '',
		addressUrl: "testline",
		requestType: "POST",
		isAllData: true,
		pastDate: jsonData
	}

	crossDomainAjax(opts, function(data) {
		console.log(JSON.stringify(data));
		if(data.result.indexOf("成功") > -1) {
			mui.toast("状态修改成功");
			var nextStatus = "";
			for(var i = 0; i < statusArr.length; i++) {
				if(statusArr[i] == currentStatus) {
					nextStatus = statusArr[i + 1];
				}
			}

			$("#changeStatus").html(nextStatus);
			$("#tel").html(currentStatus);
			upPhoto.src = "";
			hiddenEle(upPhoto);
		} else {
			mui.toast("状态修改失败");
		}

	});
}

var errorInfo = "";

function SetAbnormal() {
	token = localStorage.getItem("pid");
	console.log(imgStr.length);
	var pjson = {
		code: code,
		status: status,
		note: errorInfo,
		pid: token,
		image: errorPath
	};

	console.log(JSON.stringify(pjson));

	var jsonData = {
		op: "SetAbnormal",
		pjson: JSON.stringify(pjson)
	}

	var opts = {
		url: '',
		addressUrl: "testline",
		requestType: "POST",
		isAllData: true,
		pastDate: jsonData
	}

	crossDomainAjax(opts, function(data) {
		console.log(data);
		if(data.status == "1") {
			mui.toast("上报成功");
			errorImg.src = "";
			hidddenErrorDiv();
		} else {
			mui.toast("信息上报失败");
		}
	});
}

var selectPhoto = document.getElementById("selectPhoto");
var errorImg = document.getElementById("errorImg");

var imgPath = "";
var selectImgType = 0;
errorImg.addEventListener("tap", function() {
	selectImgType = 1;
	getPhoto();
}, false);

selectPhoto.addEventListener('tap', function() {
	selectImgType = 0;
	getPhoto();
}, false);

function getPhoto(type) {

	var btnArray = [{
		title: "拍照"
	}, {
		title: "从相册中选择"
	}];
	var text = "";
	plus.nativeUI.actionSheet({
		title: "选择图片",
		cancel: "取消",
		buttons: btnArray
	}, function(e) {
		var index = e.index;
		switch(index) {
			case 0:
				text = "取消选择图片";
				break;
			case 1:
				getImage();
				break;
			case 2:
				galleryImg();
				break;
		}
	});
}

function getImage() {
	var cmr = plus.camera.getCamera();
	cmr.captureImage(function(path) {
		plus.gallery.save(path, function() {

		}, function(e) {
			mui.toast("拍摄照片失败，请重试");
		});

		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			var imgEle;
			console.log("path==>>" + entry.fullPath);

			if(selectImgType == 0) {
				imgEle = upPhoto;
				isSelectPhoto = true;
				showEle(upPhoto);
			} else {
				isErrorPhoto = true;
				imgEle = errorImg;
			}
			plus.zip.compressImage({
					src: entry.fullPath,
					dst: entry.fullPath,
					overwrite: true,
					quality: 30
				},
				function() {
					uploaderImg(entry.fullPath);
				},
				function(error) {
					alert("图片上传失败，请重新选择！");
				});
			imgEle.src = entry.fullPath;
		}, function() {
			mui.toast("拍摄照片失败，请重试");
		});

	}, function(e) {
		mui.toast('取消拍照');
	}, {
		filename: '_doc/gallery/',
		index: 1
	});
}

function galleryImg() {
	// 从相册中选择图片
	plus.gallery.pick(function(path) {

		var imgEle;
		if(selectImgType == 0) {
			imgEle = upPhoto;
			isSelectPhoto = true;
			showEle(upPhoto);
		} else {
			isErrorPhoto = true;
			imgEle = errorImg;
		}
		imgEle.src = path;
		plus.zip.compressImage({
				src: path,
				dst: path,
				overwrite: true,
				quality: 30
			},
			function() {
				uploaderImg(path);
			},
			function(error) {
				alert("图片上传失败，请重新选择！");
			});

		//		imgPath = path;
		//		imgEle.onload = function() {
		//			imgStr = getBase64Image(imgEle, 200, 1);
		//		}

		//		var upParams = {
		//			files: [path],
		//			upload_abs_path: "/upload.php",
		//			successCallBack: function(data) {
		//				mui.toast("上传成功!");
		//				imgPath = data;
		//			},
		//			failCallBack: function(status) {
		//				mui.toast("上传失败!");
		//			}
		//		}
		//		uploadFiles(upParams, 1, 1);

	}, function(e) {
		mui.toast('取消选择图片');
	}, {
		filter: 'image'
	});
}

function uploaderImg(path) {
	plus.nativeUI.showWaiting();
	console.log(path);
	console.log(getRequestAddressUrl("filesUploader"));
	var task = plus.uploader.createUpload(getRequestAddressUrl("filesUploader"), {
			method: "POST",
			priority: 100
		},
		function(t, status) {
			plus.nativeUI.closeWaiting();
			// 上传完成
			if(status == 200) {
				console.log(JSON.stringify(t));
				var responseText = t.responseText;
				var responseJson = JSON.parse(responseText);
				if(responseJson.status == 1) {

					if(selectImgType == 0) {
						imgPath = responseJson.url;
					} else {
						errorPath = responseJson.url;
					}
					console.log(imgPath);
					mui.toast("上传成功!");
				} else {
					mui.toast("上传失败!");
				}
			} else {
				mui.toast("上传失败!");
			}
		}
	);
	var length = path.split("/").length - 1;
	var name = path.split("/")[length];
	var addType = task.addFile(path, {
		key: "Filedata",
		name: name,
		mime: "image/jpeg"
	});
	console.log("addType===>>" + addType);
	task.start();
}

mui("#policyList").on('click', 'li', function() {

	var positionPoint = this.getElementsByTagName("div")[0];

	hiddenEle(positionPoint);

	var postdata = {
		pageflag: "page_policy.html",
		itemID: this.id
	}

	var change = {
		pageUrl: "page_policyinfo.html",
		postData: postdata,
		aniShow: "fade-in"
	}

	pageChange(change);

});

var statusArr = ["未出库", "已出库", '在途', '正在供应', '已完成供应', '已签收'];

$("#changeStatus").click(function() {

	otherInfo = $("#otherInfo").val();

	if($(this).html() == "已签收") {
		return;
	}

	if(isEmpty(carCode)) {
		mui.toast("车单信息不全，请退出重试");
		return;
	}

	if(!isSelectPhoto) {
		mui.toast("请选择图片后再试");
		return;
	}

	if(isEmpty(imgPath)) {
		mui.toast("请等待图片上传");
		return;
	}
	console.log(imgPath);
	if(isHaveNet()) {
		UpdateCarStatus();
	} else {
		mui.toast("无网络连接！");
	}

});

/**
 * 创建政策列表
 * @param {Object} row
 */
function createPolicyItem(row) {
	var isHidden = "mui-hidden";
	if(!isEmpty(row.status) && row.status == "0") {
		isHidden = "";
	}
	var createLi = document.createElement("li");
	createLi.className = "mui-table-view-cell";
	createLi.id = row.msg_id;
	createLi.innerHTML = '<div class="message-position ' + isHidden + '"></div>' +
		'<div class="policy-title">' + row.title + '</div>' +
		'<div class="poilcy-time">' + row.add_time + '</div>';
	document.body.appendChild(createLi);
	insertBefore(createLi, insretPolicy);
}

var backDrop = document.getElementById("backDrop");
var errorDiv = document.getElementById("errorDiv");

backDrop.addEventListener('tap', function() {
	hidddenErrorDiv();
}, false);

$("#cancleBtn").click(function() {
	hidddenErrorDiv();
});

$("#cancleImg").bind('tap', function() {
	hidddenErrorDiv();
});

$("#errorBtn").click(function() {

	showEle(backDrop);
	showEle(errorDiv);

});

$("#submitBtn").click(function() {
	errorInfo = $("#errorMesg").val().trim();
	if(isEmpty(errorInfo)) {
		mui.toast("请填写异常信息");
		return;
	}

	if(!isErrorPhoto) {
		mui.toast("请选择图片后再试");
		return;
	}

	if(isEmpty(errorPath)) {
		mui.toast("请等待图片上传");
		return;
	}

	if(isHaveNet()) {
		SetAbnormal();
	} else {
		mui.toast("请检查网络连接");
	}

});

function hidddenErrorDiv() {
	hiddenEle(backDrop);
	hiddenEle(errorDiv);
}